package com.feather.web;

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.DataSource;

import net.sf.json.JSONSerializer;

import org.springframework.jdbc.datasource.DriverManagerDataSource;


import com.feather.core.*;
import com.feather.finder.SQLActionFinder;
import com.feather.unit.*;

public class SimpleServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	private ActionController actionController = null;
	
	private DataSource dataSource = null;
	
	private Map<Object, Object> appParams = new HashMap<Object, Object>();

	@SuppressWarnings("unchecked")
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String contextPath = getServletContext().getContextPath();
		String uri = request.getRequestURI();
		
		if(uri.startsWith(contextPath))
			uri = uri.substring(contextPath.length());
		
		Map<String, Object> params = new HashMap<String, Object>();
		for(Map.Entry<String, String[]> e : request.getParameterMap().entrySet())
		{
			params.put(e.getKey(), e.getValue()[0]);
		}
		
		try {
			Object result = actionController.doURI(uri, params);
			if(result instanceof Map)
			{
				Map<String, Object> resultMap = (Map<String, Object>) result;
				
				Object responseObject = resultMap.get("response");
				if(responseObject == null)
				{
					response.setContentType("text/html");
					response.setCharacterEncoding("utf-8");
					response.getWriter().write("response is null");
				}
				else if(responseObject instanceof String)
				{
					String responseText = (String) responseObject;
					response.setContentType("text/html");
					response.setCharacterEncoding("utf-8");
					response.getWriter().write(responseText);
				}
				else if (responseObject instanceof Map || responseObject instanceof List)
				{
					String responseText = JSONSerializer.toJSON(responseObject).toString();
					response.setContentType("application/json");
					response.setCharacterEncoding("utf-8");
					response.getWriter().write(responseText);
				}
				else
				{
					String responseText = responseObject.toString();
					response.setContentType("text/html");
					response.setCharacterEncoding("utf-8");
					response.getWriter().write(responseText);
				}
			}
			else
			{
				response.getWriter().write(result == null ? "(result == null)" : result.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void init() throws ServletException {
		try {
			String propertyFilePath = this.getInitParameter("PropertyFilePath");
			Properties prop = new Properties();
			prop.load(getServletContext().getResourceAsStream(propertyFilePath));
			appParams.putAll(prop);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		DriverManagerDataSource dmds = new DriverManagerDataSource();
		dmds.setDriverClassName((String)appParams.get("jdbc.driverClassName"));
		dmds.setUsername((String)appParams.get("jdbc.username"));
		dmds.setPassword((String)appParams.get("jdbc.password"));
		dmds.setUrl((String)appParams.get("jdbc.url"));
		dataSource = dmds;
		
		actionController = new ActionController();
		
		FileActionUnit fileActionUnit = new FileActionUnit();
		actionController.addObjectMethod(fileActionUnit);
		fileActionUnit.setRoot(getServletContext().getRealPath("/"));
		
		SQLActionUnit sqlActionUnit = new SQLActionUnit();
		actionController.addObjectMethod(sqlActionUnit);
		sqlActionUnit.setDataSource(dataSource);
		
		FreemarkerActionUnit freemarkerActionUnit = new FreemarkerActionUnit();
		actionController.addObjectMethod(freemarkerActionUnit);
		
		MapActionUnit mapActionUnit = new MapActionUnit();
		actionController.addObjectMethod(mapActionUnit);
		
		StringActionUnit stringActionUnit = new StringActionUnit();
		actionController.addObjectMethod(stringActionUnit);
		
		SQLActionFinder sqlActionFinder = new SQLActionFinder();
		actionController.addActionFinder(sqlActionFinder);
		sqlActionFinder.setSql((String)appParams.get("sqlActionFinder.sql"));
		sqlActionFinder.setDataSource(dataSource);
		
		
	}
	
	

}
